package HTTP

import (
	"SQL/util"
	"logs"
	"net/http"
)

//发送消息：
//s userID  string,talkerID string,msgContent string
//r Message string

func sendMessage(w http.ResponseWriter, r *http.Request) {

	code := Success
	info := "success"
	var information interface{}

	defer func() {
		writeResult(w, code, info, information)
	}()

	err := r.ParseForm()
	if err != nil {
		logs.Print("From:sendMessage.ParseForm:---", err.Error())
		info = "From:sendMessage.ParseForm:---error"
		code = errParseForm
		return
	}

	sender := r.Form["userID"]
	receiver := r.Form["talkerID"]
	content := r.Form["msgContent"]

	if sender == nil {
		code = errEmptyParameter
		info = "From:sendMessage:---userID is null"
		return
	}
	if receiver == nil {
		code = errEmptyParameter
		info = "From:sendMessage:---talkerID is null"
		return
	}
	if content == nil {
		code = errEmptyParameter
		info = "From:sendMessage:---msgContent is null"
		return
	}
	info, code, ok := checkOutInsertMessage(sender[0], receiver[0], content[0])
	if !ok {
		return
	}

	ok, code, info = insertMessages(sender[0], receiver[0], content[0])
	if !ok {
		return
	}
}

//插入messages 表 数据
func insertMessages(sender string, receiver string, content string) (bool, int, string) {
	info := "success"
	code := Success

	info, code, ok := checkOutInsertMessage(sender, receiver, content)
	if !ok {
		return false, code, info
	}

	sql := "insert into messages(content,sender,receiver) values ($1,$2,$3)"
	_, err := util.Exec(sql, content, sender, receiver)
	if err != nil {
		logs.Print("From:sendMessage.Exec", err.Error())
		info = "From:sendMessage.Exec---error"
		return false, errDBExecFailed, info
	}

	return true, code, info
}

func checkOutInsertMessage(userID string, talkerID string, magContent string) (string, int, bool) {

	info := "success"
	code := Success
	if ok, code, info := checkOutId(userID); !ok {
		info = "From:sendMessage.checkOutInsertMessage---userID is Invalid"
		return info, code, false
	}

	if ok, code, info := checkOutId(talkerID); !ok {
		info = "From:sendMessage.checkOutInsertMessage---talkerID is Invalid"
		return info, code, false
	}

	if magContent == "" {
		info = "From:sendMessage.checkOutInsertMessage---msgContent is empty"
		return info, errInvalidMsgContent, false
	}

	if userID == talkerID {
		info = "From:sendMessage.checkOutInsertMessage---userID is the same as talkerID"
		return info, errInvalidID, false

	}

	if info, _, ok := isUser(userID); !ok {
		info = "From:sendMessage.checkOutInsertMessage---userID is no user"
		return info, errInvalidID, false
	}

	if info, _, ok := isObject(talkerID); !ok {
		info = "From:sendMessage.checkOutInsertMessage---talkerID is no exits"
		return info, errInvalidID, false
	}

	if _, _, ok := isUser(talkerID); !ok {
		if info, code, ok := isGroupMember(userID, talkerID); !ok {
			info = "From:sendMessage.checkOutInsertMessage---userID is Invalid because userID is not the group member"
			return info, code, ok
		}
	}

	return info, code, true
}
